/**
 * @file 工单操作-跟单
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.define(['layer', 'form', 'table', 'zmnUtils', '$http'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var table = layui.table;
    var opCommonUtils = layui.list_modify_common;
    var $http = layui.$http;
    var zmnUtils = layui.zmnUtils;

    /**
     * 跟单结果列表 id 选择器名称
     * @type {string}
     */
    var TRACK_LIST_TABLE_ID = 'trackListTable';
    /**
     * 保存跟单结果 URL
     * @type {string}
     */
    var SAVE_TRACK_URL = '/work/modify/save/track.action';

    /**
     * 选择器枚举类
     * @type {{trackTypeItem: string}}
     */
    var SELECTOR_ENUM = {
        trackTypeItem: '.track-type-item',
    };

    /**
     * 跟单列表容器
     * @type {Array[]|Array}
     */
    var trackListContainer = trackList || [];

    /**
     * 表单格式化器
     * @type {object}
     */
    var tableFormatter = {
        formatLevel: function (data) {
            var level = +data.level;
            var text = zmnUtils.arabicToChinese(level) + '级';
            var levelClass = 'level-' + data.level;
            return '<span class="' + levelClass + '">' + text + '</span>';
        }
    };

    /**
     * 设置跟单选项多选框的状态
     * @param {object} $input 多选框 jQuery 对象
     * @param {object} disabled 禁用状态
     */
    function setTrackTypeCheckboxState ($input, disabled) {
        $input.prop('disabled', disabled).prop('checked', disabled);

        if (disabled) {
            $input.closest(SELECTOR_ENUM.trackTypeItem)
                .addClass('disabled');
        } else {
            $input.closest(SELECTOR_ENUM.trackTypeItem)
                .removeClass('disabled');
        }
    }

    /**
     * 使用 mapId 查询多选框
     * @param mapId
     * @returns {pe.fn.init|jQuery|HTMLElement}
     */
    function queryCheckboxByMapId (mapId) {
        return $('#track-type-' + mapId);
    }

    /**
     * 设置多个跟单选项多选框的状态
     * @param mapIdList
     * @param {object} disabled 禁用状态
     */
    function setTrackTypeCheckboxListState (mapIdList, disabled) {
        mapIdList.forEach(function (mapId) {
            var $input = queryCheckboxByMapId(mapId);
            setTrackTypeCheckboxState($input, disabled);
        });
    }

    /**
     * 初始化选选框组状态
     */
    function initPageTrackTypeCheckboxListState () {
        var mapIdList = trackList.map(function (item) {
            return item.mapId;
        });

        mapIdList.forEach(function (mapId) {
            var $input = queryCheckboxByMapId(mapId);
            $input.prop('checked', true)
                .prop('disabled', true);
        });
        setTrackTypeCheckboxListState(mapIdList, true);
        form.render();
    }


    /**
     * 注册表单验证器
     */
    function initFormVerify () {
        form.verify({
            length: function (val) {
                if (val.length > 300) {
                    return '不能超过300字'
                }
            }
        });
    }

    /**
     * 未完成跟单
     */
    function renderTrackListTable (trackList) {
        table.render({
            elem: '#' + TRACK_LIST_TABLE_ID,
            limit:10000,
            cols: [
                [
                    {field: 'trackId', hide: true},
                    {field: 'mapId', hide: true},
                    {field: 'mapName', title: '跟单内容', templet:function(d){
                            var remark = d.remark || "";
                            return d.mapName + " " + remark;
                        }},
                    {field: 'resultContent', title: '跟单结果', templet: '#input'},
                    {field: 'level', title: '跟单等级', align: 'center', width: 100, templet:  tableFormatter.formatLevel },
                    {field: 'level', title: '操作', align: 'center', width: 100, toolbar: '#tmpl-trackListTableCheckbox' },
                ]
            ],
            data: trackList,
            done: function () {
                form.render();
            }
        });
    }

    /**
     * 整理请求参数
     * @param detailDTOList 跟单选项列表
     * @returns {{orderId: jQuery, detailDTOList: *, workId: jQuery}}
     */
    function normalizeRequestParams (detailDTOList) {
        return {
            workId: $('#work-id').val(),
            orderId: $('#order-id').val(),
            detailDTOList: detailDTOList
        }
    }

    /**
     * ajax 请求
     * @param data {object} data,success,fail属性
     */
    function request(data, btn, reload) {
        $http.lockSave(SAVE_TRACK_URL, data, btn).then(function () {
            zmnUtils.layui.toastSuccess('操作成功', function () {
                reload ? location.reload() : opCommonUtils.goOperateHome();
            });
        }, (msg) => {
            layer.msg(msg);
        });
    }

    /**
     * 从数据库中删除跟单
     * @param params
     * @param btn
     * @returns {*}
     */
    function deleteTrackFromLibrary (params, btn) {
        return $http.$lockSave(SAVE_TRACK_URL, params, btn);
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        /**
         * 监听跟单内容复选框选择
         */
        form.on('checkbox(trackType)', function(data){
            if (data.elem.checked) {
                var $input = $(data.elem);
                trackListContainer.push({
                    mapId: +$input.val(),
                    mapName: $input.attr('title'),
                    level: +$input.attr('level')
                });
                renderTrackListTable(trackListContainer);
                setTrackTypeCheckboxState($input, true);
                form.render();
            }
        });

        $('.layui-form').on('change', '.track-content', function () {
            var $input = $(this);
            var mapId = $input.data('map-id');
            var trackItem = trackListContainer.find(function (item) {
                return item.mapId === +mapId;
            });

            if (trackItem) {
                trackItem.resultContent = $input.val();
            }
        });

        //监听工具条
        table.on('tool(table-track-list)', function (obj) {
            var rowData = obj.data; //获得当前行数据
            var layEvent = obj.event;

            var deleteTrackRowData = function (mapId) {
                obj.del();
                trackListContainer = table.cache[TRACK_LIST_TABLE_ID].filter(function (item) {
                    return !Array.isArray(item);
                });
                renderTrackListTable(trackListContainer);
                setTrackTypeCheckboxState(queryCheckboxByMapId(mapId), false);
                form.render('checkbox');
            };

            if (layEvent === 'delete') {
                var mapId = rowData.mapId;
                var trackId = rowData.trackId;

                if (trackId) {
                    layer.confirm('确定删除？', {
                        btn: ['确认','取消']
                    }, function (index) {
                        var trackType = Object.assign({}, rowData, {
                            deleted: 2
                        });
                        var parmas = normalizeRequestParams([trackType]);
                        deleteTrackFromLibrary(parmas).then(function () {
                            deleteTrackRowData(mapId);
                            layer.close(index);
                            zmnUtils.layui.toastSuccess('删除成功');
                        }, function (msg) {
                            zmnUtils.layui.toastError('删除跟单数据失败：' + msg);
                        });
                    }, function (index) {
                        layer.close(index);
                    });
                } else {
                    deleteTrackRowData(mapId);
                }
            }
        });

        //新的跟单
        form.on('submit(btn-submit)', function (data) {
            var formData = data.field;
            var otherTrackList = [];
            if (formData.otherTrackName) {
                otherTrackList.push({
                    mapId: formData.otherTrackMapId,
                    mapName: formData.otherTrackName,
                    level: formData.otherTrackLevel
                });
            }

            var newOrderTrackList = [].concat(trackListContainer)
                .concat(otherTrackList);

            if (!newOrderTrackList.length) {
                zmnUtils.layui.toastError('至少勾选一项或填写其他跟单内容');
                return false;
            }

            var params = normalizeRequestParams(newOrderTrackList);
            request(params, data.elem, true);
            return false;
        });
    }

    /**
     * 初始化页面
     */
    function initPage() {
        initFormVerify();
        renderTrackListTable(trackListContainer);
        initPageTrackTypeCheckboxListState();
    }

    // 程序入口
    function init() {
        // 初始化页面
        initPage();
        // 初始化事件
        initEvent();
    }

    // 初始化
    init();

    exports('oms_work_modify_track');
});
